<template>
  <div class="login-container">
    <div class="logo" />
    <div class="form">
      <h1>登录</h1>
      <el-card shadow="never" class="login-card">
        <!-- 登录方式切换 -->
        <div class="login-type">
          <el-radio-group v-model="loginType">
            <el-radio label="account">
              <i class="el-icon-user"></i>
              账号密码登录
            </el-radio>
            <el-radio label="qrcode">
              <i class="el-icon-mobile-phone"></i>
              扫码登录
            </el-radio>
          </el-radio-group>
        </div>

        <div class="login-content">
          <!-- 账号密码登录表单 -->
          <template v-if="loginType === 'account'">
            <el-form ref="form" :model="loginForm" :rules="loginRules">
              <el-form-item prop="mobile">
                <el-input v-model="loginForm.mobile" placeholder="请输入手机号" />
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="loginForm.password" show-password placeholder="请输入密码" />
              </el-form-item>
              <el-form-item prop="isAgree">
                <el-checkbox v-model="loginForm.isAgree">
                  用户平台使用协议
                </el-checkbox>
              </el-form-item>
              <el-form-item>
                <el-button style="width:350px" type="primary" @click="login">登录</el-button>
              </el-form-item>
            </el-form>
          </template>

          <!-- 扫码登录区域 -->
          <template v-if="loginType === 'qrcode'">
            <div class="qrcode-container">
              <div class="qrcode-box">
                <canvas ref="qrcodeCanvas"></canvas>
              </div>
              <p class="qrcode-tip">{{ qrcodeTip }}</p>
              <el-button v-if="needRefresh" type="primary" @click="refreshQrcode">刷新二维码</el-button>
            </div>
          </template>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getQrcodeKey, getQrcodeState } from '@/api/user'
import QRCode from 'qrcode'

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        mobile: process.env.NODE_ENV === 'development' ? '13800000002' : '',
        password: process.env.NODE_ENV === 'development' ? 'hm#qd@23!' : '',
        isAgree: process.env.NODE_ENV === 'development'
      },
      loginRules: {
        mobile: [{
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        }, {
          pattern: /^1[3-9]\d{9}$/,
          message: '手机号格式不正确',
          trigger: 'blur'

        }],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }, {
          min: 6,
          max: 16,
          message: '密码长度应该为6-16位之间',
          trigger: 'blur'

        }],
        // required只能检查 null "" undefined
        isAgree: [{
          validator: (rule, value, callback) => {
            // rule规则
            // value检查的数据 true/false
            // callback 函数 执行这个函数
            // 成功执行callback 失败也执行callback(错误对象 new Error(错误信息))
            value ? callback() : callback(new Error('没有勾选用户平台协议'))
          }
        }]
      },
      loginType: 'account',
      qrcodeKey: '',
      qrcodeTimer: null,
      qrcodeTip: '请使用手机扫描二维码登录',
      needRefresh: false
    }
  },
  methods: {
    login() {
      this.$refs.form.validate((isOK) => {
        if (isOK) {
          this.$store.dispatch("user/login", this.loginForm)
          // 跳转主页
          // this.$router.push('/')
        }
      })
    },
    // 生成二维码
    async generateQrcode() {
      try {
        const res = await getQrcodeKey()
        this.qrcodeKey = res

        // 生成二维码
        await QRCode.toCanvas(this.$refs.qrcodeCanvas, this.qrcodeKey, {
          width: 180,
          margin: 0
        })
        
        this.needRefresh = false
        this.startCheckQrcodeState()
      } catch (error) {
        console.error('生成二维码失败:', error)
        this.qrcodeTip = '生成二维码失败，请刷新重试'
        this.needRefresh = true
      }
    },
    
    // 开始检查二维码状态
    startCheckQrcodeState() {
      if (this.qrcodeTimer) {
        clearInterval(this.qrcodeTimer)
      }
      
      this.qrcodeTimer = setInterval(async () => {
        try {
          const data = await getQrcodeState(this.qrcodeKey)
          console.log(data);
          
          switch (data.codeState) {
            case 1:
              this.qrcodeTip = '请使用手机扫描二维码登录'
              break
            case 2:
              this.qrcodeTip = '已扫描，请在手机上确认登录'
              break
            case 3:
              clearInterval(this.qrcodeTimer)
              this.qrcodeTip = '登录成功，正在跳转...'
              // 保存token并跳转
              this.$store.commit('user/setToken', this.qrcodeKey)
              this.$router.push('/')
              break
            case 4:
              clearInterval(this.qrcodeTimer)
              this.qrcodeTip = '二维码已失效'
              this.needRefresh = true
              break
            case 5:
              clearInterval(this.qrcodeTimer)
              this.qrcodeTip = '已取消登录'
              this.needRefresh = true
              break
          }
        } catch (error) {
          console.error('检查二维码状态失败:', error)
        }
      }, 3000) // 每3秒检查一次状态
    },
    
    // 刷新二维码
    refreshQrcode() {
      this.generateQrcode()
    }
  },
  watch: {
    loginType(newVal) {
      if (newVal === 'qrcode') {
        this.$nextTick(() => {
          this.generateQrcode()
        })
      } else {
        if (this.qrcodeTimer) {
          clearInterval(this.qrcodeTimer)
        }
      }
    }
  },
  beforeDestroy() {
    if (this.qrcodeTimer) {
      clearInterval(this.qrcodeTimer)
    }
  }
}
</script>

<style lang="scss">
.login-container {
  display: flex;
  align-items: stretch;
  height: 100vh;

  .logo {
    flex: 3;
    background: rgba(38, 72, 176) url(../../assets/common/login_back.png) no-repeat center / cover;
    border-top-right-radius: 60px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: center;
    padding: 0 100px;

    .icon {
      background: url(../../assets/common/logo.png) no-repeat 70px center / contain;
      width: 300px;
      height: 50px;
      margin-bottom: 50px;
    }

    p {
      color: #fff;
      font-size: 18px;
      margin-top: 20px;
      width: 300px;
      text-align: center;
    }
  }

  .form {
    flex: 2;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding-left: 176px;

    .el-card {
      border: none;
      padding: 0;
    }

    h1 {
      padding-left: 20px;
      font-size: 24px;
    }

    .el-input {
      width: 350px;
      height: 44px;

      .el-input__inner {
        background: #f4f5fb;
      }
    }

    .el-checkbox {
      color: #606266;
    }
  }
}

.login-card {
  width: 400px;
  padding: 20px !important;
  
  .login-type {
    text-align: center;
    margin-bottom: 30px;
    border-bottom: 1px solid #eee;
    padding-bottom: 20px;

    .el-radio-group {
      display: flex;
      justify-content: space-around;

      .el-radio {
        margin-right: 0;
        padding: 10px 20px;
        border-radius: 4px;
        transition: all 0.3s;

        &:hover {
          background: #f5f7fa;
        }

        i {
          margin-right: 5px;
          font-size: 18px;
          vertical-align: middle;
        }

        &.is-checked {
          background: #f0f5ff;
          color: #409eff;
        }
      }
    }
  }

  .login-content {
    min-height: 320px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .qrcode-container {
    width: 100%;
    padding: 20px 0;
    
    .qrcode-box {
      width: 200px;
      height: 200px;
      margin: 0 auto;
      padding: 10px;
      background: #fff;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
      
      canvas {
        width: 100%;
        height: 100%;
      }
    }
    
    .qrcode-tip {
      margin-top: 20px;
      color: #606266;
      font-size: 14px;
    }

    .el-button {
      margin-top: 20px;
      width: 120px;
    }
  }

  .el-form {
    width: 100%;
  }
}
</style>
